from microbit import *
import machine
import radio

radio.on()
radio.config(length=128)

img = [
  Image("90909:09990:00900:00900:00900"),
  Image("00000:09090:00900:00900:00900"),
  Image("00000:"*5)
]

def c_send(text='', num=0, serial=False):
    if serial:
        sn = int.from_bytes(machine.unique_id(), 'big')
    else:
        sn = 0
    msg = 'text="{}" num="{}" ser="{}"'.format(text, num, hex(sn))
    radio.send(msg)

def c_receive():
    buf = radio.receive_full()
    if buf:
        try:
            d = str(buf[0], '')
            p0 = d.find('\x01\x00\x01text="')
            if p0 == -1:
                return ('', 0, 0, 0, -128)
            else:
                p1 = d.find('" num="')
                p2 = d.find('" ser="')
                dt = d[p0+9:p1]
                dn = d[p1+7:p2]
                ds = d[p2+7:-1]
                return (dt, int(dn), int(ds), buf[1], buf[2])
        except:
            return
    else:
        return

while True:
    if button_a.was_pressed():
        c_send("name=Alice", 12)

    if button_b.was_pressed():
        c_send('', running_time() % 65536)

    dat = c_receive()
    if dat:
        display.show(img)
        print(dat)

    sleep(1000)